package com.manelrodriguez.applications.eurostoxx50.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

import android.content.Context;
import android.util.Log;

import com.manelrodriguez.applications.eurostoxx50.R;
import com.manelrodriguez.applications.eurostoxx50.to.Empresa;

public class DescargaCotizacionesYahoo {
	SimpleDateFormat sdf,sdf2;
	
	public DescargaCotizacionesYahoo(){
		super();
		sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
		sdf2 = new SimpleDateFormat("dd/MM HH:mm ");
	}

	public int descargar(URL param, ArrayList<Empresa> m_empresas, Map<String,Empresa> hash_empresas, Context context) {
		String [] partes = null;
		 try {
			 URL url = param;
			 BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
			 String line = null;
			 TimeZone tz = TimeZone.getDefault();
			 
			 //Date now = new Date();
			 int offset = tz.getOffset(Calendar.ZONE_OFFSET)/3600000 - Constantes.UTC_OFFSET_YAHOO;
			 //int offset = tz.getOffset(now.getTime())/3600000 - Constantes.UTC_OFFSET_YAHOO;
			 do {
				try{
     		    	partes = null;
     		    	line = buff.readLine();
     		    	if(line!=null) partes = line.replace("\"", "").split(",");
     		    	if(partes!=null && partes.length == 10){
     		    		Date date = sdf.parse(partes[2] + " " + partes[3].replace("am", "").replace("pm", ""));
     		    		date.setHours(date.getHours()+offset);
     			    	Empresa cotizacion = new Empresa();
     			    	cotizacion.setCompanyName(Empresa.getIdEmpresaString(partes[0],context));
     			    	cotizacion.setStockSymbol(partes[0]);
     			    	cotizacion.setLastTradeAmount(partes[1]);
     			    	cotizacion.setLastTradeDateTime(sdf2.format(date));
     			    	cotizacion.setStockChange(partes[4]);
     			    	cotizacion.setOpenAmount(partes[5]);
     			    	cotizacion.setDayHigh(partes[6]);
     			    	cotizacion.setDayLow(partes[7]);
     			    	cotizacion.setStockVolume(partes[8]);
     			    	cotizacion.setChangePercent(partes[9]);
     			    	if(m_empresas!=null) m_empresas.add(cotizacion);
     			    	if(hash_empresas!=null) hash_empresas.put(cotizacion.getStockSymbol(), cotizacion);
     		    	}
				}catch (ParseException e) {
					Log.e("Parseando datos",context.getString(R.string.errorFechas));
				}
 		    } while (line != null);
		 }catch (MalformedURLException e) {
			 return StocksURLS.ERROR_URL;
		 } catch (IOException e) {
			 return StocksURLS.ERROR_CONECTION;
		 }
		 return StocksURLS.RESULT_OK;
	}
}
